﻿using System;
using System.Linq;
using Moq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CodeCamp.Mailers;
using CodeCamp.Models.UserMailer;
using CCM = CodeCamp.Model;
using SNM = System.Net.Mail;
using Mvc.Mailer;

namespace CodeCamp.Tests.Mailer
{
    [TestClass]
    public class MvcMailerTests
    {
        private Mock<UserMailer> _userMailerMock;

        [TestInitialize]
        public void Initialize()
        {
            _userMailerMock = new Mock<UserMailer>();
            //per https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide
            //CallBase will ensure real implementations are called for methods that are not mocked out.
            _userMailerMock.CallBase = true;
            MailerBase.IsTestModeEnabled = true;
        }

        private static class TestMessageValues
        {
            internal const string FirstName = "Joe";
            internal const string FromAddress = "testfrom@rgood.net";
            internal const string ToAddress = "testto@rgood.net";
            internal const string WelcomeSubject = "Welcome to this test";
        }

        [TestMethod]
        public void Test_TestMessage()
        {
            const string emailViewSimple = "BasicTest";

            Mvc.Mailer.EmptyHttpContext.MockUrl = "http://localhost/Home/";
            //Arrange: Moq out the PopulateBody method
            _userMailerMock.Setup(mailer => mailer.PopulateBody(It.IsAny<SNM.MailMessage>(), emailViewSimple, null));

            MvcMailMessage mailMessage = null;
            {
                CCM.EmailItem emailItem = new CCM.EmailItem()
                {
                    FirstName = TestMessageValues.FirstName,
                    ReplyToAddress = TestMessageValues.FromAddress,
                    Subject = TestMessageValues.WelcomeSubject,
                    EmailTo = TestMessageValues.ToAddress,
                    EmailView = emailViewSimple
                };
                //Act
                CodeCamp.Models.Email.EmailContentItem contentItem = CodeCamp.Controllers.EmailController.PrepareEmailContentItem(emailItem);
                mailMessage = _userMailerMock.Object.CodeCampEventMessage(contentItem);
            }
            
            //Assert
            Assert.IsNotNull(mailMessage);
            _userMailerMock.VerifyAll();
            object modelObject = _userMailerMock.Object.ViewData.Model;
            Assert.IsNotNull(modelObject);
            Assert.AreEqual(typeof(CCM.EmailItem), modelObject.GetType());
            CCM.EmailItem mailerModel = modelObject as CCM.EmailItem;
            Assert.IsNotNull(mailerModel);
            Assert.AreEqual(TestMessageValues.FirstName, mailerModel.FirstName);
            Assert.AreEqual(TestMessageValues.WelcomeSubject, mailMessage.Subject);
            Assert.AreEqual(TestMessageValues.ToAddress, mailMessage.To.First().ToString());
        }
    }
}
